package com.timedomain.him.remake.utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import android.content.SharedPreferences;
import android.os.Build;
import com.timedomain.him.remake.Program;
import com.timedomain.him.remake.receiver.MorningCallAlarmReceiver;

import java.io.File;
import java.util.*;

public class MorningCallManager {

    public static long getNextTime(){
        if(AppSettings.firstRun){
            return -1;
        }
        if(AppSettings.nightChat && AppSettings.nightChatRequiredMorningCall){
            return AppSettings.manualMorningCallDate;
        }
        else{
            if(!AppSettings.nightChat && !AppSettings.morningCallIsManual){
                long date =
                        TimeUtils.dateStampToTimeStamp(TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone()));

                if(AppSettings.morningCallDateStamp == 0){
                    AppSettings.morningCallDateStamp = TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone());
                }

                if(AppSettings.morningCallDateStamp >= TimeUtils.toDateStamp(TimeUtils.getTimeStampIgnoreTimeZone())){
                    date += 86400000L;
                }

                long hourAndMinute = (AppSettings.morningCallHour - TimeUtils.hoursThatBeginOfDay) * 3600000L +
                        AppSettings.morningCallMinute * 60000L;

                return hourAndMinute + date;
            }
            return -1;
        }
    }


    // 逻辑：
    /*
    周六周日：100%周末电话
    工作日：70%非周末电话+30%工作日电话
    */

    public static String pullOneNewMorningCall(Context ctx){

        String targetPath = "";


        if(TimeUtils.isWeekend(TimeUtils.getTimeStampIgnoreTimeZone())){
            if(TimeUtils.isSaturnday(TimeUtils.getTimeStampIgnoreTimeZone())){
                targetPath = "weekend";
            }
            else{
                targetPath = "weekend";
            }
        }
        else{
            if (Math.random() < 0.3d) {
                targetPath = "weekday";
            }
            else {
                targetPath = "neural";
            }
        }
        return MorningCallFreqCounter.getMorningCall(ctx,targetPath);
    }



    public static void setNextMorningCall(Context ctx){
        long nextTime = getNextTime();
        if(!AppSettings.firstRun){
            AppSettings.saveSettings(ctx);
        }
        Intent intent = new Intent(ctx, MorningCallAlarmReceiver.class);
        ScheduledEventUtils.scheduleAlarmClock(ctx,431,intent,nextTime);
    }



    // 统计每个早安电话的触发次数
    // 这样就能实现如果更新了新的早安电话，就会优先触发
    public static class MorningCallFreqCounter{


        private static SharedPreferences getStore(Context ctx){

            return ctx.getSharedPreferences("morningcall_freq",Context.MODE_PRIVATE);
        }

        private static int GetMorningCallTime(Context ctx,String name){
            return getStore(ctx).getInt(name,-1);
        }
        private static void IncreaseMorningCallTime(Context ctx,String name,int count){
            getStore(ctx).edit().putInt(name,count).apply();
        }

        public static class MorningCallFreqPair{
            // 从来不写Getter和Setter，直接public就是干，奥里给
            public String name;
            // int32，最大值2147483647，从安装起预计可以使用6亿年。
            public int count;

            public MorningCallFreqPair(String name, int count) {
                this.name = name;
                this.count = count;
            }
        }

        private static List<String> getAllMorningCallByType(String type){
            List<String> files = FileUtils.listFiles(FileUtils.pathCombine("morningcall",type),(dir,f) -> f.toLowerCase().endsWith(".ogg"));
            return files;
        }

        public static List<MorningCallFreqPair> dumpData(Context ctx){
            List<MorningCallFreqPair> pairs = new ArrayList<>();
            SharedPreferences sp = getStore(ctx);
            for (String item : sp.getAll().keySet()) {
                pairs.add(new MorningCallFreqPair(item,sp.getInt(item,0)));
            }
            return pairs;
        }

        public static void restoreData(Context ctx,List<MorningCallFreqPair> data){
            SharedPreferences sp = getStore(ctx);
            SharedPreferences.Editor editor = sp.edit();
            for (MorningCallFreqPair item :
                    data) {
                editor.putInt(item.name,item.count);
            }
            editor.apply();
        }

        // 已经过严格论证：
        // 如果有新添加的早安电话，则优先触发，并放到当前一批的下一批中
        // 否则从当前一批早安电话中选择，触发后放到下一批中
        public static String getMorningCall(Context ctx,String type){
            List<String> availables = getAllMorningCallByType(type);
            int min = Integer.MAX_VALUE;
            int secondaryMin = Integer.MAX_VALUE;
            List<MorningCallFreqPair> minPairs = new ArrayList<>();
            for (String item : availables) {
                int count = GetMorningCallTime(ctx,item);
                if(count < min){
                    min = count;
                    minPairs.clear();
                }
                if(count == min){
                    minPairs.add(new MorningCallFreqPair(item,count));
                }
            }
            for (String item : availables) {
                int count = GetMorningCallTime(ctx,item);
                if(count != min && count < secondaryMin){
                    secondaryMin = count;
                }
            }
            if(secondaryMin == Integer.MAX_VALUE){
                secondaryMin = min+1;
            }
            Collections.shuffle(minPairs);
            MorningCallFreqPair randomOne = minPairs.get(0);
            if(randomOne.count == -1){

                IncreaseMorningCallTime(ctx,randomOne.name,secondaryMin);

            }
            else{
                IncreaseMorningCallTime(ctx, randomOne.name,  randomOne.count+1);
            }
            return randomOne.name;
        }


    }


}

